package com.app.web.sys.banner;

import com.app.utils.base.j2se.Common;
import com.app.utils.base.j2se.Convert;
import com.app.utils.base.j2se.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

@Service
public class BannerManager{
    @Autowired
    private BannerService bannerModel;
    private Map<String,List<Map<String, Object>>> list = new HashMap<>();

    /**
     * 根据位置获取该位置下所有广告
     */
    public List<Map<String, Object>> list(int placeId,int app){
        return list.containsKey(app+"_"+placeId)?list.get(app+"_"+placeId):new ArrayList<>();
    }

    @PostConstruct
    public void init(){
        load();
        new Thread(()->{
            while (true) {
                try {
                    Thread.sleep(5*6*1000);
                    load();
                } catch (InterruptedException e) {
                    Logger.error("加载banner失败",e);
                }
            }
        }).start();
    }

    private void load(){
        try {
            //获取所有广告
            List<Map<String, Object>> banners = bannerModel.list();
            //如果会空直接返回
            if(Common.isEmpty(banners)){
                this.list = new HashMap<>();
                return;
            }
            //初始化返回的组装数据
            Map<String,List<Map<String,Object>>> result = new HashMap<>();
            for(Map<String,Object> banner:banners){
                int placeId = Convert.objToInt(banner.get("placeId"));//获取广告位置
                int app = Convert.objToInt(banner.get("post"));//获取端
                //验证是否存在该位置 不存在则初始化
                if(!result.containsKey(app+"_"+placeId)){
                    result.put(app+"_"+placeId,new ArrayList<>());
                }
                //在该位置追加广告
                result.get(app+"_"+placeId).add(banner);
            }
            this.list = result;
        } catch (Exception e) {
            Logger.error("加载banner列表", e);
        }
    }

}
